package com.xuesaieducation.zshddemo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.gensee.download.VodDownLoadEntity;
import com.gensee.download.VodDownLoadStatus;
import com.gensee.download.VodDownLoader;
import com.gensee.utils.StringUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DownloadListActivity extends AppCompatActivity implements VodDownLoader.OnDownloadListener
{
    @BindView(R.id.list)
    ListView mListView;
    @BindView(R.id.no_data)
    TextView noData;

    private VodDownLoader mVodDownLoader;
    private SharedPreferences preferences;
    MyAdapter mMyAdapter;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_list);
        ButterKnife.bind(this);

        init();

        List<com.gensee.download.VodDownLoadEntity> tmp = mVodDownLoader.getDownloadList();
        if(tmp != null && tmp.size() > 0)
        {
            mMyAdapter = new MyAdapter(this, mVodDownLoader.getDownloadList());
            mListView.setAdapter(mMyAdapter);
        }else
        {
            noData.setVisibility(View.VISIBLE);
        }
    }

    private void init()
    {
        preferences = getSharedPreferences("gensee_config", MODE_PRIVATE);
        mHandler = new Handler();
        //如果需要区分多用户，请使用带用户id的instance进行初始化，默认情况下用户id为0
        mVodDownLoader = VodDownLoader.instance(this, this, String.valueOf(getExternalFilesDir(null)));
        // 启动已存在且未完成的任务
        mVodDownLoader.download();
    }

    @Override
    public void onDLFinish(String downLoadId, String localPath)
    {
        preferences.edit().putString(downLoadId, localPath).apply();
        mHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                mMyAdapter.notifyData(mVodDownLoader.getDownloadList());
            }
        });
    }


    @Override
    public void onDLPosition(String downLoadId, final int percent)
    {
        // 下载过程中
        mHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                mMyAdapter.notifyData(mVodDownLoader.getDownloadList());
            }
        });
    }

    public void onDLPrepare(String downLoadId)
    {
        mHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                mMyAdapter.notifyData(mVodDownLoader.getDownloadList());
            }
        });
    }

    @Override
    public void onDLStart(String s)
    {

    }

    @Override
    public void onDLStop(String s)
    {

    }

    @Override
    public void onDLError(String s, int i)
    {

    }

    class MyAdapter extends BaseAdapter
    {
        private List<VodDownLoadEntity> entities = null;
        private Context mContext;

        public MyAdapter(Context mContext, List<VodDownLoadEntity> l)
        {
            this.mContext = mContext;
            entities = l;
        }

        public void notifyData(List<VodDownLoadEntity> entities)
        {
            this.entities = entities;
            notifyDataSetChanged();
        }

        @Override
        public int getCount()
        {
            return entities == null ? 0 : entities.size();
        }

        @Override
        public Object getItem(int position)
        {
            return entities.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent)
        {

            if (null == convertView)
            {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem, null);
            }
            final VodDownLoadEntity entity = (VodDownLoadEntity) getItem(position);
            TextView mTextView = (TextView) convertView.findViewById(R.id.downloadcontextid);
            TextView mProTextView = (TextView) convertView.findViewById(R.id.downloadprogressitem);
            ImageView deleteButton = (ImageView) convertView.findViewById(R.id.deleteDownload);
            ImageView stopButton = (ImageView) convertView.findViewById(R.id.stopdownload);
            final int status = entity.getnStatus();
            if (status == VodDownLoadStatus.FINISH.getStatus())
            {
                stopButton.setVisibility(View.INVISIBLE);
            } else
            {
                stopButton.setVisibility(View.VISIBLE);
                if (status == VodDownLoadStatus.STOP.getStatus())
                {
                    stopButton.setImageResource(R.drawable.downloading);
                } else if (status == VodDownLoadStatus.BEGIN.getStatus()
                        || status == VodDownLoadStatus.START.getStatus())
                {
                    stopButton.setImageResource(R.drawable.download_pause);
                } else
                {
                    stopButton.setImageResource(R.drawable.downloading);
                }
            }
            ImageView playButton = (ImageView) convertView.findViewById(R.id.palydownload);
            mTextView.setText(entity.getVodSubject() + " ");
            mProTextView.setText(entity.getnPercent() + "%");
            deleteButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    mVodDownLoader.delete(entity.getDownLoadId());
                    // 同时删除已经存放的本地路径
                    preferences.edit().remove(entity.getDownLoadId()).apply();
                    // 删除之后刷新
                    notifyData(mVodDownLoader.getDownloadList());
                }
            });

            stopButton.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    if (status == VodDownLoadStatus.FAILED.getStatus()
                            || status == VodDownLoadStatus.STOP.getStatus()
                            || status == VodDownLoadStatus.DENY.getStatus())
                    {
                        mVodDownLoader.download(entity.getDownLoadId());
                    } else if (status == VodDownLoadStatus.BEGIN.getStatus()
                            || status == VodDownLoadStatus.START.getStatus())
                    {
                        mVodDownLoader.stop(entity.getDownLoadId());
                    }
                }
            });

            playButton.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {
                    String loacalPath = preferences.getString(
                            entity.getDownLoadId(), "");
                    // 离线播放
                    if (!StringUtil.isEmpty(loacalPath))
                    {
                        Intent intent = new Intent(DownloadListActivity.this, GenSeePlayActivity.class);
                        intent.putExtra("play_path", loacalPath);
                        intent.putExtra("isLive", false);
                        startActivity(intent);
                    }
                }
            });
            return convertView;
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if(mHandler != null)
            mHandler.removeCallbacksAndMessages(null);
    }
}
